<template>
  <div class="bigbox">
    <div class="leftbox bgcfff">
      <el-input
        style="margin-bottom: 10px"
        placeholder="输入关键字进行过滤"
        v-model="filterText"
      >
      </el-input>
      <el-tree
        :data="treeList"
        :props="defaultProps"
        @node-click="handleNodeClick"
        :filter-node-method="filterNode"
        node-key="name"
        ref="tree"
      >
        <span slot-scope="{ node, data }" class="slot-t-node">
          <template>
            <img
              :src="'data:image/png;base64,' + data.iconBase64"
              style="
                width: 16px;
                height: 16px;
                margin-right: 5px;
                vertical-align: bottom;
              "
            />
            <span style="font-size: 14px !important">{{ node.label }}</span>
          </template>
        </span>
      </el-tree>
    </div>
    <div class="rightbox">
      <div class="top">
        <el-form
          ref="form"
          :model="form"
          label-position="left"
          label-width="80px"
        >
          <el-row :gutter="20">
            <el-col :span="5">
              <el-form-item label="时间间隔">
                <el-radio-group
                  style="width: 200px"
                  size="small"
                  v-model="form.dateType"
                >
                  <el-radio-button label="1">日</el-radio-button>
                  <el-radio-button label="2">月</el-radio-button>
                  <el-radio-button label="3">年</el-radio-button>
                  <el-radio-button label="4">自定义</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="日期">
                <el-date-picker
                  size="small"
                  v-show="form.dateType !== '4'"
                  v-model="form.dateTime"
                  :type="
                    form.dateType === '1'
                      ? 'date'
                      : form.dateType === '2'
                      ? 'month'
                      : 'year'
                  "
                  placeholder="选择日期"
                  :format="
                    form.dateType === '1'
                      ? 'yyyy-MM-dd'
                      : form.dateType === '2'
                      ? 'yyyy-MM'
                      : 'yyyy'
                  "
                  :value-format="
                    form.dateType === '1'
                      ? 'yyyy-MM-dd'
                      : form.dateType === '2'
                      ? 'yyyy-MM'
                      : 'yyyy'
                  "
                >
                </el-date-picker>
                <el-date-picker
                  size="small"
                  v-show="form.dateType === '4'"
                  v-model="form.formTime"
                  type="daterange"
                  @change="changeFormDate"
                  style="width: 100%"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <el-form-item label="">
                <el-button type="primary" size="small" @click="addTags"
                  >添加对比</el-button
                >
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="main bgcfff">
        <div class="tagsbox">
          <div
            class="tags"
            v-for="item in tags"
            :key="item.companyNo + item.date"
          >
            <i class="el-icon-close" @click="delItem(item)"></i>
            <div class="l" :style="{ 'background-color': item.color }"></div>
            <div class="tag-content">
              <div class="text">{{ item.name }}</div>
              <div class="line" v-if="form.dateType !== '4'"></div>
              <div class="date" v-if="form.dateType !== '4'">
                {{ item.date }}
              </div>
            </div>
          </div>
        </div>
        <div class="echartsbox">
          <nt-echart :loading="loading" :options="lineOptions"></nt-echart>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getDeviceChildrenApi, getDeviceRootApi } from '@/api'
import { exportexcel } from '@/utils/excel'
import ntEchart from '@/components/nt-echart.vue'
import dayjs from 'dayjs'
import { getLineApi } from '@/api/Intelligence-maintenance/Auxiliary-analysis/Loadline-contrast'
export default {
  name: 'LoadLineContrast',
  components: { ntEchart },
  data() {
    return {
      filterText: '',
      treeList: [],
      defaultProps: {
        label: 'name'
      },
      form: {
        dateTime: dayjs().format('YYYY-MM-DD'),
        dateType: '1',
        formTime: [
          dayjs().startOf('month').format('YYYY-MM-DD'),
          dayjs().format('YYYY-MM-DD')
        ]
      },
      checkItem: {},
      loading: false,
      tags: [],
      lineList: [],
      series: []
    }
  },
  computed: {
    lineOptions() {
      console.log(1)
      return {
        title: {
          top: '3%',
          text: '负荷曲线'
        },
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          top: '10%',
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {},
        xAxis: {
          type: 'category'
        },
        yAxis: {
          type: 'value'
        },
        series: this.series
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    'form.dateType': {
      handler(newVal) {
        this.tags = []
        this.form.dateTime =
          newVal === '1'
            ? dayjs().format('YYYY-MM-DD')
            : newVal === '2'
            ? dayjs().format('YYYY-MM')
            : dayjs().format('YYYY')
      },
      deep: true
    },
    tags: {
      async handler(newVal) {
        await this.getLine()
      },
      deep: true
    }
  },
  created() {
    this.getTreeList()
  },
  methods: {
    changeFormDate(val) {
      this.tags = []
      this.series = []
    },
    delItem(item) {
      this.tags = this.tags.filter(
        (tag) => tag.companyNo !== item.companyNo || tag.date !== item.date
      )
    },
    addTags() {
      if (!this.checkItem.companyNo) {
        return this.$message({
          message: '请先选择企业',
          type: 'warning',
          duration: 1000
        })
      }
      const existingTag = this.tags.find(
        (tag) =>
          tag.companyNo === this.checkItem.companyNo &&
          tag.date === this.form.dateTime
      )

      if (!existingTag) {
        this.tags.push({
          date: this.form.dateTime,
          color: this.getRandomColor(),
          ...this.checkItem
        })
      } else {
        this.$message({
          message: '请勿重复添加',
          type: 'warning',
          duration: 1000
        })
      }
    },
    async getLine() {
      if (this.tags.length === 0) {
        this.lineList = []
        this.series = []
        return
      }
      this.loading = true
      const res =
        this.form.dateType !== '4'
          ? await getLineApi({
              companyNoAndTime: this.tags
                .map((i) => `${i.companyNo},${i.date},${i.color};`)
                ?.join(''),
              dateType: this.form.dateType
            })
          : await getLineApi({
              companyNoAndTime: this.tags
                .map((i) => `${i.companyNo},${i.color},`)
                ?.join(','),
              dateType: this.form.dateType,
              fromDate: this.form.formTime[0],
              toDate: this.form.formTime[1]
            })
      this.lineList = res.data.list
      console.log('this.lineList', this.lineList)
      this.series = this.lineList.map((item) => {
        let name = item.name
        console.log(name)
        const color = name.split(';').pop()
        name = name.split(';')[0]
        console.log(color)

        console.log(name)
        return {
          name: name,
          type: 'line',
          smooth: true,
          color: [color],
          data: item.datalist.map((i) => [
            this.form.dateType === '1'
              ? dayjs(i.timeReading).format('HH:mm')
              : this.form.dateType === '2'
              ? dayjs(i.timeReading).format('D日')
              : this.form.dateType === '3'
              ? dayjs(i.timeReading).format('M月')
              : dayjs(i.timeReading).format('YYYY-MM-DD'),
            i.valueReading
          ])
        }
      })
      console.log('this.series', this.series)

      this.loading = false
    },
    async getTreeList() {
      const res = await getDeviceRootApi()
      const res2 = await getDeviceChildrenApi(res.data.list[0])
      this.treeList = res2.data.list
    },
    handleNodeClick(val) {
      console.log(val)
      this.checkItem = val
    },
    daochu() {
      this.form.dateType !== '4'
        ? exportexcel(
            '/pio-microservice-biz/pio/load/analysis/user/exportExcel',
            {
              dateType: this.form.dateType,
              dateTime: this.form.dateTime,
              industryLargeCategory: this.form.industryLargeCategory,
              industryType: this.form.industryType
            },
            '用户负荷分析'
          )
        : exportexcel(
            '/pio-microservice-biz/pio/load/analysis/user/exportExcel',
            {
              dateType: this.form.dateType,
              industryLargeCategory: this.form.industryLargeCategory,
              industryType: this.form.industryType,
              fromDate: this.form.formTime[0],
              toDate: this.form.formTime[1]
            },
            '用户负荷分析'
          )
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    // 随机颜色
    getRandomColor() {
      const letters = '0123456789ABCDEF'
      let color = '#'
      for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)]
      }
      return color
    }
  }
}
</script>

<style lang="scss" scoped>
.bgcfff {
  background-color: #fff;
}
.bigbox {
  display: flex;
  padding: 10px;
  width: 100vw;
  height: 100vh;
  .leftbox {
    width: 300px;
    padding: 20px;
    margin-right: 10px;
  }
  .rightbox {
    flex: 1;
    display: flex;
    flex-direction: column;
    background-color: #f1f1f1;
    height: 100%;
    .top {
      background-color: #fff;
      padding: 20px;
      box-sizing: border-box;
      height: 80px !important;
      width: 100% !important;
      margin-bottom: 10px;
    }
    .main {
      flex: 1;
      display: flex;
      flex-direction: column;
      width: 100%;
      padding: 10px;
      .tagsbox {
        display: flex;
        width: 100%;
        overflow-x: scroll;
        padding: 10px;
        height: 120px;
        background-color: #dedede;
        .tags {
          position: relative;
          display: flex;
          min-width: 150px;
          height: 100%;
          background-color: #fff;
          border-radius: 5px;
          margin-right: 10px;
          .el-icon-close {
            position: absolute;
            right: 2px;
            top: 2px;
            cursor: pointer;
          }
          .l {
            width: 10px;
            height: 100%;
            border-radius: 3px 0px 0px 3px;
          }
          .tag-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-around;
            width: auto;
            height: 100%;
            padding: 10px;
            font-size: 14px;
            text-align: center;
            .line {
              width: 100%;
              height: 1px;
              background-color: #e9e9e9;
            }
          }
        }
      }
      .echartsbox {
        flex: 1;
        width: 100%;
      }
    }
  }
}
</style>
